﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using ERP_RORZE_TOOL.BizLogic;
using ERP_RORZE_TOOL.Common;
using ERP_RORZE_TOOL.Common.ValueObject;
using ERP_RORZE.Tool.UserControls;

namespace ERP_RORZE.Tool.Forms
{
	public partial class frm_SupplierEdit : DevExpress.XtraEditors.XtraForm
	{
		public string SupplierId;
		public string SupplierName;
		private ucSupplier parent;

		public frm_SupplierEdit(ucSupplier fSupplier)
		{
			InitializeComponent();
			parent = fSupplier;
			this.CancelButton = this.btCancel;
		}

		private void btSave_Click(object sender, EventArgs e)
		{
			SupplierHelper helper = new SupplierHelper(new Supplier());
			if(GetData(helper.ValueObject))
			{
				Utilities.Timer timer = new Utilities.Timer();

				if(helper.Update() > 0)
				{
					timer.lb= lblStatus;
					timer.ShowHideLabel(lblStatus, 3000, Color.Blue, ToolConstants.Message.UpdateSuccess);
				}
				else
				{
					timer.lb= lblStatus;
					timer.ShowHideLabel(lblStatus, 3000, Color.Red, ToolConstants.Message.UpdateFailed);
				}
				parent.BindDatatoGrid();
			}
		}

		private void btCancel_Click(object sender, EventArgs e)
		{
			this.Close();
		}

		private void frm_SupplierEdit_Load(object sender, EventArgs e)
		{
			BindData();
		}

		#region Private methods

		private bool CheckDuplicate(string id)
		{
			SupplierHelper helper = new SupplierHelper(new Supplier());
			helper.ValueObject.SupplierID = id;
			DataTable dt = helper.GetOne();
			if(dt.Rows.Count > 0)
				return true;
			return false;

		}
		private bool GetData(Supplier o)
		{
			#region Check valid
			if(Utilities.IsNullOrEmpty(txtSupplierID.Text.Trim()))
			{
				MessageBox.Show(ToolConstants.Message.Supplier.SupplierIdCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

			if(Utilities.IsNullOrEmpty(txtSupplierName.Text.Trim()))
			{
				MessageBox.Show(ToolConstants.Message.Supplier.SupplierNameCantEmpty, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
				return false;
			}

			if(string.Compare(txtSupplierID.Text.Trim(), SupplierId) != 0)
			{
				if(CheckDuplicate(txtSupplierID.Text.Trim()))
				{
					MessageBox.Show(ToolConstants.Message.Supplier.SupplierHasExisted, ToolConstants.Form.MessageBox.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
					return false;
				}
			}
			#endregion

			o.TempId = txtSupplierID.Text;
			o.SupplierID = SupplierId;
			o.SupplierName = txtSupplierName.Text;

			return true;
		}

		private void BindData()
		{
			txtSupplierID.Text =SupplierId;
			txtSupplierName.Text = SupplierName;
		}

		#endregion

	}
}